package com.ll.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.ll.base.dto.ApiResultDTO;
import com.ll.base.dto.NameDTO;
import com.ll.base.exception.CustomRunTimeException;
import com.ll.base.util.RedisUtil;
import com.ll.domain.classbase.biz.CourseDomainService;
import com.ll.domain.dingtalk.base.DingTalkUserBaseService;
import com.ll.domain.dingtalk.biz.DingTalkRobotDomainService;
import com.ll.domain.dingtalk.constant.RobotCmdConstant;
import com.ll.domain.dingtalk.utils.AccessTokenUtil;
import com.ll.domain.user.base.UserBaseService;
import com.ll.domain.user.biz.UserDomainService;
import com.ll.domain.user.dto.UserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import static com.ll.domain.dingtalk.constant.RobotCmdConstant.Cmd.*;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "机器人API")
public class DingRobotController {

    private final UserDomainService userDomainService;
    private final UserBaseService userBaseService;
    private final DingTalkRobotDomainService dingTalkRobotDomainService;
    private final DingTalkUserBaseService dingTalkUserBaseService;


    @RequestMapping(value = "/robots")
    @ApiOperation(value = "机器人接收消息")
    public ApiResultDTO helloRobots(@RequestBody(required = false) JSONObject json, HttpServletRequest request) {
        System.out.println(json);
        String content = json.getJSONObject("text").get("content").toString().replaceAll(" ", "");
        if (dingTalkRobotDomainService.checkSign(request.getHeader("timestamp"), request.getHeader("sign"))) {
            String sessionWebhook = json.getString("sessionWebhook");
            DingTalkClient client = new DefaultDingTalkClient(sessionWebhook);
            String dingUid = json.getString("senderStaffId");
            UserDTO userDTO = null;
            if (dingUid != null) {
                userDTO = userDomainService.getByDingUid(dingUid);
                if (userDTO == null) {
                    String token = AccessTokenUtil.getToken();
                    userDTO = dingTalkUserBaseService.getByUserId(token, dingUid);
                    userBaseService.register(userDTO);
                }
            } else {
                String name = json.getString("senderNick");
                userDTO = userDomainService.getByName(NameDTO.builder().name(name).build());
            }
            String sndContent = this.handlerCmd(userDTO, content);
            dingTalkRobotDomainService.sendMsg(client, sndContent);
        }
        return ApiResultDTO.success();
    }

    /**
     * 处理消息
     * @param userDTO
     * @param content
     * @return
     */
    private String handlerCmd(UserDTO userDTO, String content) {
        String sndContent = RobotCmdConstant.DEFAULT_MSG;
        if (userDTO == null) {
            return "用户信息获取失败，请从小程序报名";
        }
        try {
            //课程表
            if (content.contains(COURSE_LIST) || content.contains("排期") || content.contains("课表")) {
                sndContent = dingTalkRobotDomainService.buildCourseList();
                //报名
            } else if (content.startsWith(APPLY_PREFIX) || content.startsWith("+")) {
                sndContent = dingTalkRobotDomainService.buildApply(userDTO, content);

                //取消报名
            } else if (content.startsWith(CANCEL_APPLY_PREFIX) || content.startsWith("-")) {
                sndContent = dingTalkRobotDomainService.buildCancelApply(userDTO, content);

                //签到
            } else if (content.startsWith(SIGNUP_PREFIX)) {
                sndContent = dingTalkRobotDomainService.buildSignUp(userDTO, content);

                //打榜
            } else if (content.contains(DB)) {
                sndContent = dingTalkRobotDomainService.buildDB(userDTO, content);
            }
        }catch (CustomRunTimeException ex){
            log.error("机器人处理消息业务异常：{}", ex.getErrorMsg());
            sndContent = ex.getErrorMsg();
        }

        return sndContent;
    }


}


